package com.content.scaffold.common.mybatis.query;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xiaojl
 */
@Getter
@Setter
public class PageQueryParams<T> extends Page<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -1710273706052960025L;
    private static final int MAX_LIMIT = 999;

    private PageQuery query;

    public PageQueryParams() {
        this(new PageQuery());
    }

    public PageQueryParams(PageQuery query) {
        this(query, false);
    }

    public PageQueryParams(PageQuery query, boolean disableSort) {
        super(query.getPage(), query.getSize());
        this.query = query;

        if (!disableSort && StringUtils.isNotBlank(query.getSort())) {
            String sortField = com.content.scaffold.common.utils.StringUtils.camelToUnderline(query.getSort());
            String order = StringUtils.isNotBlank(query.getOrder()) ? query.getOrder() : "desc";

            if ("asc".equalsIgnoreCase(order)) {
                this.addOrder(OrderItem.asc(sortField));
            } else {
                this.addOrder(OrderItem.desc(sortField));
            }
        }
    }

    public int getPage() {
        return Math.max((int) this.getCurrent(), 1);
    }

    public int getLimit() {
        return Math.min((int) this.getSize(), MAX_LIMIT);
    }

    public <R> PageQueryParams<R> convertNewPage(Function<T, R> convertFn) {
        PageQueryParams<R> pageParams = new PageQueryParams<>(this.query);
        pageParams.setTotal(this.getTotal());

        if (!this.getRecords().isEmpty()) {
            pageParams.setRecords(this.getRecords().stream()
                    .map(convertFn)
                    .collect(Collectors.toList()));
        }

        return pageParams;
    }
}